<template>
  <div class="search-container">
    <!-- 搜索区------------------ -->
    <!-- 表单的用处：在手机端访问时，输入法键盘里会出现 搜索确认按钮 -->
    <form action="/">
      <van-search
        v-model="searchKey"
        show-action
        placeholder="请输入搜索关键词"
        @search="onSearch"
        @cancel="onCancel"
        @clear="isShowResult = false"
        @focus="isShowResult = false"
      >
        <van-icon
          name="arrow-left"
          slot="left"
          @click="$router.push('/home')"
        />
      </van-search>
    </form>
    <!-- 搜索结果------------------ -->
    <SearchResult :searchKey="searchKey" v-if="isShowResult" />
    <!-- 搜索建议------------------ -->
    <SearchSuggestion
      @setKeyword="setKeyWord"
      :keyword="searchKey"
      v-else-if="searchKey"
    />
    <!-- 搜索历史------------------ -->
    <SearchHistory @sonSearch="onSearch" v-else :historyList="historyList" />
  </div>
</template>

<script>
import SearchHistory from "@/views/search/components/search-history.vue";
import SearchSuggestion from "@/views/search/components/search-suggestion.vue";
import SearchResult from "@/views/search/components/search-result.vue";

// 导入存取localStorage方法
import { setItem, getItem } from "@/utils/storage.js";

export default {
  name: "search",
  props: {},
  data() {
    return {
      // 搜索框文字
      searchKey: "",
      // 是否显示结果组件
      isShowResult: false,
      historyList: getItem(this.$conf.SEARCH_HISTORY) || [],
    };
  },

  methods: {
    // 子组件选中set关键字
    setKeyWord(newWord) {
      // 将被选中的关键字设置给搜索框
      this.searchKey = newWord;
      // 显示结果组件，隐藏建议组件
      this.isShowResult = true;
    },
    // 搜索框回车触发事件
    onSearch(kw) {
      this.searchKey=kw
      // 检查当前关键字是否在数组中存在，如果存在则删除之前的，重新添加新的
      let delIndex = this.historyList.findIndex((x) => x === kw);
      // console.log('重复的下标',delIndex);
      // 如果存在，则删除
      if (delIndex > -1) {
        this.historyList.splice(delIndex, 1);
      }
      // 将关键字添加到数组头中
      this.historyList.unshift(this.searchKey);
      // 清空搜索文本框
      // this.searchKey = "";
      // 显示搜索结果组件
      this.isShowResult = true;
    },

    // 点击取消按钮事件
    onCancel() {
      console.log("取消");
      // 关闭搜索组件
      this.isShowResult = false;
      // 清空文本框
      this.searchKey = "";
    },
  },
  computed: {},
  watch: {
    // 侦听搜索历史数组，一旦发生改变，就保存到本地
    historyList(v) {
      // console.log(v);
      setItem(this.$conf.SEARCH_HISTORY, v);
    },
  },
  components: { SearchHistory, SearchSuggestion, SearchResult },
};
</script>

<style lang="less" scoped>
.search-container {
  .van-search {
    background-color: #0094ff;
    .van-search__action {
      background-color: #0094ff;
      color: #fff;
    }
    .van-icon-arrow-left {
      color: #fff;
      font-size: 28px;
      margin-right: 10px;
    }
  }
}
</style>